package com.fsd.admin.service.impl;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.annotation.Resource;

import com.fsd.admin.dao.z_domainDao;
import com.fsd.admin.model.z_domain;
import com.fsd.admin.service.Z_projectmemberService;
import com.fsd.admin.service.z_domainService;
import com.fsd.core.util.DateTimeUtil;
import com.fsd.core.util.PdfUtil;
import com.google.gson.Gson;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import org.activiti.engine.HistoryService;
import org.activiti.engine.IdentityService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.impl.persistence.entity.ProcessDefinitionEntity;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.activiti.engine.runtime.ProcessInstance;
import org.hibernate.Criteria;
import org.hibernate.criterion.Disjunction;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Property;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.fsd.core.service.impl.BaseServiceImpl;
import com.fsd.core.common.BusinessException;
import com.fsd.core.util.ParametersUtil;
import com.fsd.admin.model.A_Employee;
import com.fsd.admin.model.Z_project;
import com.fsd.admin.model.Z_teamanduser;
import com.fsd.admin.service.Z_projectService;
import com.fsd.admin.service.Z_teamanduserService;
import com.fsd.admin.dao.Z_projectDao;

@Service("z_projectServiceImpl")
public class Z_projectServiceImpl extends BaseServiceImpl<Z_project, String> implements Z_projectService{

    private String depict = "项目管理";
    
    @Resource(name = "z_projectDaoImpl")
	public void setBaseDao(Z_projectDao Z_projectDao) {
		super.setBaseDao(Z_projectDao);
	}
	
	@Resource(name = "z_projectDaoImpl")
	private Z_projectDao objectDao;

	@Resource(name = "z_domainDaoImpl")
	private z_domainDao domainDao;

	@Resource(name = "z_domainServiceImpl")
	private z_domainService domainService;

	@Autowired
	private Z_projectmemberService projectmemberService;
    
	private List<z_domain> domainList = new ArrayList<>();

	@Autowired
	private RuntimeService activitiRuntimeService;

	@Autowired
	private IdentityService activitiIdentityService;

	@Autowired
	private HistoryService activitiHistoryService;

	@Autowired
	private RepositoryService activitiRepositoryService;
    /**
	 * 加载申报分页数据
	 * @param param
	 * @return
	 * @throws Exception
	 */
    @Override
	public ParametersUtil getObjectApplyPageList(ParametersUtil param, A_Employee employee) throws Exception{
		Criteria c = objectDao.createCriteria();
		if(!employee.isIsadmin()){
			c.add(Restrictions.eq("f_addemployeeid", employee.getId()));
		}
		c.add(Restrictions.eq("f_delete", "0"));
		c.addOrder(Order.asc("f_code"));
		if(param.getJsonData() != null && !"".equals(param.getJsonData())){
			Gson gs = new Gson();
			Map objectMap = gs.fromJson(param.getJsonData(), Map.class);
			if(objectMap.get("name") != null && !"".equals(objectMap.get("name"))){
				Disjunction disjunction = Restrictions.disjunction();
				disjunction.add(Restrictions.or(Restrictions.like("f_name", "%" + objectMap.get("name") + "%")));
				disjunction.add(Restrictions.or(Restrictions.like("f_code", "%" + objectMap.get("name") + "%")));
				c.add(disjunction);
			}
		}
		return objectDao.findPager(param , c);
	}

	/**
	 * 加载中期检查分页数据
	 * @param param
	 * @param employee
	 * @return
	 * @throws Exception
	 */
	@Override
	public ParametersUtil getObjectMiddlePageList(ParametersUtil param, A_Employee employee) throws Exception{
		Criteria c = objectDao.createCriteria();
		c.add(Restrictions.eq("f_statusid", "projectstate-tjysh"));
		if(!employee.isIsadmin()){
			c.add(Restrictions.eq("f_addemployeeid", employee.getId()));
		}
		c.add(Restrictions.eq("f_delete", "0"));
		c.addOrder(Order.asc("f_code"));
		if(param.getJsonData() != null && !"".equals(param.getJsonData())){
			Gson gs = new Gson();
			Map objectMap = gs.fromJson(param.getJsonData(), Map.class);
			if(objectMap.get("name") != null && !"".equals(objectMap.get("name"))){
				Disjunction disjunction = Restrictions.disjunction();
				disjunction.add(Restrictions.or(Restrictions.like("f_name", "%" + objectMap.get("name") + "%")));
				disjunction.add(Restrictions.or(Restrictions.like("f_code", "%" + objectMap.get("name") + "%")));
				c.add(disjunction);
			}
		}
		return objectDao.findPager(param , c);
	}

	/**
	 * 加载申报分页数据
	 * @param param
	 * @return
	 * @throws Exception
	 */
	@Override
	public ParametersUtil getObjectPageList(ParametersUtil param, A_Employee employee) throws Exception{
		Criteria c = objectDao.createCriteria();
		c.add(Restrictions.eq("f_delete", "0"));
		if(!employee.isIsadmin()){
			if("true".equals(employee.getDepartmentadmin())){
				Disjunction disjunction = Restrictions.disjunction();
				disjunction.add(Restrictions.or(Restrictions.eq("f_branchid", employee.getBranchid())));
				disjunction.add(Restrictions.or(Restrictions.eq("f_addemployeeid", employee.getId())));
				c.add(disjunction);
			}else{
				Disjunction disjunction = Restrictions.disjunction();
				disjunction.add(Restrictions.or(Restrictions.eq("f_teacherid", employee.getId())));
				disjunction.add(Restrictions.or(Restrictions.eq("f_teacherid2", employee.getId())));
				disjunction.add(Restrictions.or(Restrictions.eq("f_addemployeeid", employee.getId())));
				c.add(disjunction);
			}
		}
		c.addOrder(Order.asc("f_code"));
		if(param.getJsonData() != null && !"".equals(param.getJsonData())){
			Gson gs = new Gson();
			Map objectMap = gs.fromJson(param.getJsonData(), Map.class);
			if(objectMap.get("name") != null && !"".equals(objectMap.get("name"))){
				Disjunction disjunction = Restrictions.disjunction();
				disjunction.add(Restrictions.or(Restrictions.like("f_name", "%" + objectMap.get("name") + "%")));
				disjunction.add(Restrictions.or(Restrictions.like("f_code", "%" + objectMap.get("name") + "%")));
				c.add(disjunction);
			}
			if(objectMap.get("queryid") != null && !"".equals(objectMap.get("queryid"))){
				if(objectMap.get("queryid").equals("wfz")){
					Disjunction disjunction = Restrictions.disjunction();
					disjunction.add(Restrictions.or(Property.forName("f_classifyid").isNull()));
					c.add(disjunction);
				}else{
					c.add(Restrictions.eq("f_classifyid", objectMap.get("queryid")));
				}
			}
		}
		return objectDao.findPager(param , c);
	}
    
    /**
	 * 加载分页数据(项目已立项)
	 * @param param
	 * @return
	 * @throws Exception
	 */
    @Override
	public ParametersUtil getObjectPageListProspectus(ParametersUtil param, A_Employee employee) throws Exception{
		Criteria c = objectDao.createCriteria();
		c.add(Restrictions.eq("f_delete", "0"));
		c.add(Restrictions.eq("f_statusid", "5"));
		c.add(Restrictions.eq("f_statusname", "项目立项"));
		c.addOrder(Order.asc("f_code"));
		if(param.getJsonData() != null && !"".equals(param.getJsonData())){
			Gson gs = new Gson();
			Map objectMap = gs.fromJson(param.getJsonData(), Map.class);
			if(objectMap.get("txt") != null && !"".equals(objectMap.get("txt"))){
				Disjunction disjunction = Restrictions.disjunction();
				disjunction.add(Restrictions.or(Restrictions.like("f_name", "%" + objectMap.get("name") + "%")));
				disjunction.add(Restrictions.or(Restrictions.like("f_code", "%" + objectMap.get("name") + "%")));
				c.add(disjunction);
			}
		}
		return objectDao.findPager(param , c);
	}
    
    /**
	 * 编辑对象
	 * @param obj
	 * @param employee
	 * @throws Exception
	 */
	@Override
	public Z_project save(String rootpath, ParametersUtil param, Z_project obj, A_Employee employee) throws Exception{
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(param.getJsonData(), Map.class);
		String status = objectMap.get("status").toString();
        if(obj.getId() != null && !"".equals(obj.getId())){
            //修改
            Z_project old_obj = objectDao.get(obj.getId());
			if(status.equals("projectstate-cg")){
				old_obj.setF_statusid("0");
				old_obj.setF_statusname("草稿");
			}else if(status.equals("projectstate-tjwsh")){
				List<Z_project> list = objectDao.queryByHql("from Z_project where f_delete = '0' and f_name = '" + obj.getF_name() + "' and f_statusid = '1'");
				if (list.size() > 0){
					throw new BusinessException("该项目名称已经存在！");
				}
				old_obj.setF_statusid("1");
				old_obj.setF_statusname("提交未审核");
			}
			old_obj.setF_name(obj.getF_name());
			if(!old_obj.getF_typeid().equals(obj.getF_typeid())){
				String code = getCode(obj.getF_typeid());
				while (true) {
					List<Z_project> codeList = objectDao.queryByHql("from Z_project where f_code = '" + code + "' ");
					if (codeList.size() > 0){
						code = getCode(obj.getF_typeid());
					}else {
						break;
					}
				}
				old_obj.setF_code(code);
			}
			old_obj.setF_typeid(obj.getF_typeid());
			old_obj.setF_typename(obj.getF_typename());

			int index = 1;
			z_domain domain = domainService.get(obj.getF_typeid1());
			domainList.clear();
			getFather(domain);
			for (int i = domainList.size()-1; i >= 0; i--) {
				z_domain temp = domainList.get(i);
				if(index == 1){
					old_obj.setF_typeid1(temp.getId());
					old_obj.setF_typename1(temp.getTitle());
					old_obj.setF_typeid2("");
					old_obj.setF_typename2("");
					old_obj.setF_typeid3("");
					old_obj.setF_typename3("");
				}else if(index == 2){
					old_obj.setF_typeid2(temp.getId());
					old_obj.setF_typename2(temp.getTitle());
					old_obj.setF_typeid3("");
					old_obj.setF_typename3("");
				}else if(index == 3){
					old_obj.setF_typeid3(temp.getId());
					old_obj.setF_typename3(temp.getTitle());
				}else{
					throw new BusinessException("学科领域节点选择不可多于三级，请联系管理员解决！");
				}
				index++;
			}

			old_obj.setF_sourceid(obj.getF_sourceid());
			old_obj.setF_sourcename(obj.getF_sourcename());
			old_obj.setF_teamid(obj.getF_teamid());
			old_obj.setF_teamname(obj.getF_teamname());
			old_obj.setF_teacherid(obj.getF_teacherid());
			old_obj.setF_teachername(obj.getF_teachername());
			old_obj.setF_teacherid2(obj.getF_teacherid2());
			old_obj.setF_teachername2(obj.getF_teachername2());
			old_obj.setF_studentnumber(obj.getF_studentnumber());
			old_obj.setF_leaderid(obj.getF_leaderid());
			old_obj.setF_leadername(obj.getF_leadername());
			old_obj.setF_leaderphone(obj.getF_leaderphone());
			old_obj.setF_email(obj.getF_email());
			old_obj.setF_starttime(obj.getF_starttime());
			old_obj.setF_stoptime(obj.getF_stoptime());
			old_obj.setF_adddate(this.getData());
			old_obj.setF_abstract(obj.getF_abstract());
			old_obj.setF_gist(obj.getF_gist());
			old_obj.setF_scheme(obj.getF_scheme());
			old_obj.setF_achievement(obj.getF_achievement());
			old_obj.setF_trait(obj.getF_trait());
			old_obj.setF_feature(obj.getF_feature());
			old_obj.setF_schedule(obj.getF_schedule());
			old_obj.setF_money_zjf(obj.getF_money_zjf());
			old_obj.setF_money_czbk(obj.getF_money_czbk());
			old_obj.setF_money_xxbk(obj.getF_money_xxbk());
			old_obj.setF_money_jtf(obj.getF_money_jtf());
			old_obj.setF_money_jtfbz(obj.getF_money_jtfbz());
			old_obj.setF_money_tszlf(obj.getF_money_tszlf());
			old_obj.setF_money_tszlfbz(obj.getF_money_tszlfbz());
			old_obj.setF_money_ysf(obj.getF_money_ysf());
			old_obj.setF_money_ysfbz(obj.getF_money_ysfbz());
			old_obj.setF_money_bgyp(obj.getF_money_bgyp());
			old_obj.setF_money_bgypbz(obj.getF_money_bgypbz());
			old_obj.setF_money_hyf(obj.getF_money_hyf());
			old_obj.setF_money_hyfbz(obj.getF_money_hyfbz());
			old_obj.setF_money_syclfbz(obj.getF_money_syclfbz());
			old_obj.setF_money_qt(obj.getF_money_qt());
			old_obj.setF_money_qtbz(obj.getF_money_qtbz());
            objectDao.update(old_obj);
			if("1".equals(old_obj.getF_statusid())){
				startActiviti(old_obj);
			}
			return old_obj;
        }else{
            //添加
			if(status.equals("projectstate-cg")){
				obj.setF_statusid("0");
				obj.setF_statusname("草稿");
			}else if(status.equals("projectstate-tjwsh")){
				List<Z_project> list = objectDao.queryByHql("from Z_project where f_delete = '0' and f_name = '" + obj.getF_name() + "' and f_statusid = '1'");
				if (list.size() > 0){
					throw new BusinessException("该项目名称已经存在！");
				}
				obj.setF_statusname("提交未审核");
				obj.setF_statusid("1");
			}
			int index = 1;
			z_domain domain = domainService.get(obj.getF_typeid1());
			domainList.clear();
			getFather(domain);
			for (int i = domainList.size()-1; i >= 0; i--) {
				z_domain temp = domainList.get(i);
				if(index == 1){
					obj.setF_typeid1(temp.getId());
					obj.setF_typename1(temp.getTitle());
				}else if(index == 2){
					obj.setF_typename2(temp.getTitle());
					obj.setF_typeid2(temp.getId());
				}else if(index == 3){
					obj.setF_typeid3(temp.getId());
					obj.setF_typename3(temp.getTitle());
				}else{
					throw new BusinessException("学科领域节点选择不可多于三级，请联系管理员解决！");
				}
				index++;
			}
			DateTimeUtil dateTimeUtil = new DateTimeUtil();
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
			String year = String.valueOf(dateTimeUtil.getYear());

			String code = getCode(obj.getF_typeid());
            obj.setId(this.getUUID());
			obj.setF_code(code);
			obj.setF_starttime(dateFormat.format(new Date()));
			obj.setF_stoptime(year+"1231");
            obj.setF_adddate(this.getData());
			obj.setF_addemployeeid(employee.getId());
			obj.setF_branchid(employee.getBranchid());
			obj.setF_delete("0");
			objectDao.save(obj);

			if("1".equals(obj.getF_statusid())){
				startActiviti(obj);
			}
			return obj;
        }
    }

	/**
	 * 保存项目基本信息
	 * @param param
	 * @param obj
	 * @param employee
	 * @return
	 * @throws Exception
	 */
	@Override
	public Z_project saveInfo(ParametersUtil param, Z_project obj, A_Employee employee) throws Exception{
		if(obj.getId() != null && !"".equals(obj.getId())){
			//修改
			Z_project old_obj = objectDao.get(obj.getId());
			old_obj.setF_name(obj.getF_name());
			old_obj.setF_typeid(obj.getF_typeid());
			old_obj.setF_typename(obj.getF_typename());
			old_obj.setF_typeid1(obj.getF_typeid1());
			old_obj.setF_typename1(obj.getF_typename1());

			List<Z_project> list = objectDao.queryBySql1("select * from z_project where f_name = ? and id <> ?", obj.getF_name(), obj.getId());
			if (list.size() > 0){
				throw new BusinessException("该项目名称已经存在！");
			}
			objectDao.update(old_obj);
			return old_obj;
		}else{
			List<Z_project> list = objectDao.queryBySql1("select * from z_project where f_name = ? ", obj.getF_name());
			if (list.size() > 0){
				throw new BusinessException("该项目名称已经存在！");
			}
			DateTimeUtil dateTimeUtil = new DateTimeUtil();
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
			String year = String.valueOf(dateTimeUtil.getYear());
			String code = getCode(obj.getF_typeid());

			obj.setId(this.getUUID());
			obj.setF_code(code);
			obj.setF_starttime(dateFormat.format(new Date()));
			obj.setF_stoptime(year+"1231");
			obj.setF_adddate(this.getData());
			obj.setF_addemployeeid(employee.getId());
			obj.setF_branchid(employee.getBranchid());
			obj.setF_statusid("0");
			obj.setF_statusname("草稿");

			obj.setF_abstract("一、项目简介（200字以内，项目研究的目的和主要研究内容）");
			obj.setF_gist("二、申请理由（800字以内，包括自身/团队具备的知识、条件、特长、兴趣、前期准备、项目研究的国内外研究现状和发展动态等）");
			obj.setF_scheme("三、项目方案（1500字左右，包括项目研究的主要问题、拟解决的途径、人员分工、预期成果等，创业训练项目还需包括商业策划、运行等内容）\n" +
					"1.项目研究的主要问题\n" +
					"2.项目拟解决的途径\n" +
					"3.人员分工\n" +
					"4.预期成果\n");
			obj.setF_feature("四、简述特色与创新点");
			obj.setF_schedule("五、项目进度安排（包括详细的计划安排）");
			obj.setF_delete("0");
			objectDao.save(obj);
			return obj;
		}
	}

	/**
	 * 保存项目负责人信息
	 * @param param
	 * @param obj
	 * @param employee
	 * @return
	 * @throws Exception
	 */
	@Override
	public Z_project saveLeader(ParametersUtil param, Z_project obj, A_Employee employee) throws Exception{
		if(obj.getId() != null && !"".equals(obj.getId())){
			//修改
			String sql = "select * from Z_project where f_leaderid = ? and f_delete = ? and id <> ?";
			List<Z_project> list = objectDao.queryBySql1(sql, obj.getF_leaderid(), "0", obj.getId());
			if(list != null && list.size() > 0){
				//throw new BusinessException(list.get(0).getF_leadername() + "已经是《"+ list.get(0).getF_name() +"》项目的项目负责人，每个人只能负责一个项目，请确认后重新提交！");
			}

			Z_project old_obj = objectDao.get(obj.getId());
			old_obj.setF_leaderid(obj.getF_leaderid());
			old_obj.setF_studentnumber(obj.getF_studentnumber());
			old_obj.setF_leadername(obj.getF_leadername());
			old_obj.setF_leaderclass(obj.getF_leaderclass());
			old_obj.setF_leadercollege(obj.getF_leadercollege());
			old_obj.setF_leaderphone(obj.getF_leaderphone());
			old_obj.setF_leaderresponsibility(obj.getF_leaderresponsibility());
			objectDao.update(old_obj);
			return old_obj;
		}else{
			throw new BusinessException("系统错误，请联系管理员");
		}
	}

	/**
	 * 保存第一指导老师信息
	 * @param param
	 * @param obj
	 * @param employee
	 * @return
	 * @throws Exception
	 */
	@Override
	public Z_project saveTeacher(ParametersUtil param, Z_project obj, A_Employee employee) throws Exception{
		if(obj.getId() != null && !"".equals(obj.getId())){
			//修改
			Z_project old_obj = objectDao.get(obj.getId());
			old_obj.setF_teacherid(obj.getF_teacherid());
			old_obj.setF_teachername(obj.getF_teachername());
			old_obj.setF_teacherduty(obj.getF_teacherduty());
			old_obj.setF_teacherunit(obj.getF_teacherunit());
			old_obj.setF_teacherphone(obj.getF_teacherphone());
			old_obj.setF_teacheremail(obj.getF_teacheremail());
			objectDao.update(old_obj);
			return old_obj;
		}else{
			throw new BusinessException("系统错误，请联系管理员");
		}
	}

	/**
	 * 保存第二指导老师信息
	 * @param param
	 * @param obj
	 * @param employee
	 * @return
	 * @throws Exception
	 */
	@Override
	public Z_project saveTeacher2(ParametersUtil param, Z_project obj, A_Employee employee) throws Exception{
		if(obj.getId() != null && !"".equals(obj.getId())){
			//修改
			Z_project old_obj = objectDao.get(obj.getId());
			old_obj.setF_teacherid2(obj.getF_teacherid2());
			old_obj.setF_teachername2(obj.getF_teachername2());
			old_obj.setF_teacherduty2(obj.getF_teacherduty2());
			old_obj.setF_teacherunit2(obj.getF_teacherunit2());
			old_obj.setF_teacherphone2(obj.getF_teacherphone2());
			old_obj.setF_teacheremail2(obj.getF_teacheremail2());
			objectDao.update(old_obj);
			return old_obj;
		}else{
			throw new BusinessException("系统错误，请联系管理员");
		}
	}

	/**
	 * 保存校外第一指导老师信息
	 * @param param
	 * @param obj
	 * @param employee
	 * @return
	 * @throws Exception
	 */
	@Override
	public Z_project saveOutTeacher(ParametersUtil param, Z_project obj, A_Employee employee) throws Exception{
		if(obj.getId() != null && !"".equals(obj.getId())){
			//修改
			Z_project old_obj = objectDao.get(obj.getId());
			old_obj.setF_outteacherid(obj.getF_outteacherid());
			old_obj.setF_outteachername(obj.getF_outteachername());
			old_obj.setF_outteacherduty(obj.getF_outteacherduty());
			old_obj.setF_outteacherunit(obj.getF_outteacherunit());
			old_obj.setF_outteacherphone(obj.getF_outteacherphone());
			old_obj.setF_outteacheremail(obj.getF_outteacheremail());
			objectDao.update(old_obj);
			return old_obj;
		}else{
			throw new BusinessException("系统错误，请联系管理员");
		}
	}

	/**
	 * 保存校外第二指导老师信息
	 * @param param
	 * @param obj
	 * @param employee
	 * @return
	 * @throws Exception
	 */
	@Override
	public Z_project saveOutTeacher2(ParametersUtil param, Z_project obj, A_Employee employee) throws Exception{
		if(obj.getId() != null && !"".equals(obj.getId())){
			//修改
			Z_project old_obj = objectDao.get(obj.getId());
			old_obj.setF_outteacherid2(obj.getF_outteacherid2());
			old_obj.setF_outteachername2(obj.getF_outteachername2());
			old_obj.setF_outteacherduty2(obj.getF_outteacherduty2());
			old_obj.setF_outteacherunit2(obj.getF_outteacherunit2());
			old_obj.setF_outteacherphone2(obj.getF_outteacherphone2());
			old_obj.setF_outteacheremail2(obj.getF_outteacheremail2());
			objectDao.update(old_obj);
			return old_obj;
		}else{
			throw new BusinessException("系统错误，请联系管理员");
		}
	}

	/**
	 * 保存项目简介
	 * @param param
	 * @param obj
	 * @param employee
	 * @return
	 * @throws Exception
	 */
	@Override
	public Z_project saveAbstract(ParametersUtil param, Z_project obj, A_Employee employee) throws Exception{
		if(obj.getId() != null && !"".equals(obj.getId())){
			//修改
			Z_project old_obj = objectDao.get(obj.getId());
			old_obj.setF_abstract(obj.getF_abstract());
			objectDao.update(old_obj);
			return old_obj;
		}else{
			throw new BusinessException("系统错误，请联系管理员");
		}
	}

	/**
	 * 保存申请理由
	 * @param param
	 * @param obj
	 * @param employee
	 * @return
	 * @throws Exception
	 */
	@Override
	public Z_project saveGist(ParametersUtil param, Z_project obj, A_Employee employee) throws Exception{
		if(obj.getId() != null && !"".equals(obj.getId())){
			//修改
			Z_project old_obj = objectDao.get(obj.getId());
			old_obj.setF_gist(obj.getF_gist());
			objectDao.update(old_obj);
			return old_obj;
		}else{
			throw new BusinessException("系统错误，请联系管理员");
		}
	}

	/**
	 * 保存项目方案
	 * @param param
	 * @param obj
	 * @param employee
	 * @return
	 * @throws Exception
	 */
	@Override
	public Z_project saveScheme(ParametersUtil param, Z_project obj, A_Employee employee) throws Exception{
		if(obj.getId() != null && !"".equals(obj.getId())){
			//修改
			Z_project old_obj = objectDao.get(obj.getId());
			old_obj.setF_scheme(obj.getF_scheme());
			objectDao.update(old_obj);
			return old_obj;
		}else{
			throw new BusinessException("系统错误，请联系管理员");
		}
	}

	/**
	 * 保存特色与创新点
	 * @param param
	 * @param obj
	 * @param employee
	 * @return
	 * @throws Exception
	 */
	@Override
	public Z_project saveFeature(ParametersUtil param, Z_project obj, A_Employee employee) throws Exception{
		if(obj.getId() != null && !"".equals(obj.getId())){
			//修改
			Z_project old_obj = objectDao.get(obj.getId());
			old_obj.setF_feature(obj.getF_feature());
			objectDao.update(old_obj);
			return old_obj;
		}else{
			throw new BusinessException("系统错误，请联系管理员");
		}
	}

	/**
	 * 保存项目进度安排
	 * @param param
	 * @param obj
	 * @param employee
	 * @return
	 * @throws Exception
	 */
	@Override
	public Z_project saveSchedule(ParametersUtil param, Z_project obj, A_Employee employee) throws Exception{
		if(obj.getId() != null && !"".equals(obj.getId())){
			//修改
			Z_project old_obj = objectDao.get(obj.getId());
			old_obj.setF_schedule(obj.getF_schedule());
			objectDao.update(old_obj);
			return old_obj;
		}else{
			throw new BusinessException("系统错误，请联系管理员");
		}
	}

	/**
	 * 提交项目
	 * @param param
	 * @throws Exception
	 */
	@Override
	public void saveProjectSubmit(String rootpath, ParametersUtil param, A_Employee employee) throws Exception{
		if(param.getJsonData() != null && !"".equals(param.getJsonData())){
			Gson gs = new Gson();
			Map objectMap = gs.fromJson(param.getJsonData(), Map.class);
			if(objectMap.get("projectid") != null && !"".equals(objectMap.get("projectid")) && objectMap.get("type") != null && !"".equals(objectMap.get("type"))){
				String projectId = objectMap.get("projectid").toString();
				String type = objectMap.get("type").toString();
				Z_project project = this.get(projectId);
				if("cg".equals(type)){
					project.setF_statusid("0");
					project.setF_statusname("草稿");
					this.update(project);
				}
				if("tj".equals(type)){
					project.setF_statusid("1");
					project.setF_statusname("提交待审核");
					this.update(project);
					startActiviti(project);
				}
			}else{
				throw new BusinessException("系统错误，请联系管理员");
			}
		}
	}


	/**
	 * 启动项目审核工作流
	 * @param obj
	 */
    public void startActiviti(Z_project obj){
		Map<String, Object> variables = new HashMap<String,Object>();
		// 指导老师ID
		variables.put("input", obj.getF_teacherid());
		String key = "xmtjlc";
		String objId = key+"."+ obj.getId();
		activitiIdentityService.setAuthenticatedUserId(obj.getF_leaderid());
		activitiRuntimeService.startProcessInstanceByKey(key,objId,variables);
	}

    /**
	 * 删除对象
	 * @param parameters
	 * @throws Exception
	 */
	@Override
	public void delObject(ParametersUtil parameters, A_Employee employee) throws Exception{
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		ArrayList<String> dir = (ArrayList<String>) objectMap.get("ids");
		for (String id : dir) {
			this.delete(id);
			projectmemberService.delObjectByProjectId(id);
		}
	}
    
    /**
	 * 根据ID加载对象
	 * @param parameters
	 * @return
	 * @throws Exception
	 */
	@Override
	public Z_project getObjectById(ParametersUtil parameters) throws Exception{
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		if(objectMap.get("id") == null && "".equals(objectMap.get("id"))){
			throw new BusinessException(depict + "获取缺少ID参数!");
		}
		Z_project obj = objectDao.get(objectMap.get("id").toString());
		if(obj == null){
			throw new BusinessException(depict + "数据不存在!");
		}
		return obj;
	}

	/**
	 * 生成code
	 * @return
	 */
	private String getCode(String type) {
		String code = "DC";
		DateTimeUtil dateTimeUtil = new DateTimeUtil();
		String year = String.valueOf(dateTimeUtil.getYear());
		code = code + year.substring(2, year.length());
		code = code + "11807";
		if(type.equals("cxxlxm")){
			code = code + "CX";
		}else if(type.equals("cyxlxm")){
			code = code + "CY";
		}else if(type.equals("cysjxm")){
			code = code + "CS";
		}
		int count = this.getTotalCount().intValue();
		if(count < 10){
			code = code + "00" + (count + 1);
		}else if(count >= 10 && count < 100){
			code = code + "0" + (count + 1);
		}else{
			code = code + (count + 1);
		}
		return code;
	}

	/**
	 * 获取父节点
	 * @param obj
	 * @throws Exception
	 */
	private void getFather(z_domain obj) throws Exception{
		if(obj != null){
			if(!"0".equals(obj.getParentid())){
				domainList.add(obj);
				obj = domainDao.get(obj.getParentid());
				getFather(obj);
			}
		}
	}

	/**
	 * 更新项目状态
	 * @param projectId
	 * @param status
	 * @throws Exception
	 */
	@Override
	public void updateProjectStatus(String projectId, String status) throws Exception{
		Z_project project = this.get(projectId);
		if("fqsq".equals(status)){
			project.setF_statusid("projectstate-xmzz");
			project.setF_statusname("项目终止");
			this.update(project);
		}else if("shtg".equals(status)){
			project.setF_statusid("projectstate-tjysh");
			project.setF_statusname("提交已审核");
			this.update(project);
		}
	}

	/**
	 * 项目立项
	 * @param ids
	 * @param typeid
	 * @param money
	 * @throws Exception
	 */
	@Override
	public void updateProjectApproval(String ids, String typeid, String money, String f_schooltypeid, String f_schooltypename) throws Exception{
		if("xj".equals(typeid)){
			String sql = "update z_project set f_isschool = 'true', f_schoolmoney = ?, f_schooltypeid = ?, f_schooltypename = ? where id in('"+ ids +"')";
			objectDao.executeSql(sql, money, f_schooltypeid, f_schooltypename);
		}else if("sj".equals(typeid)){
			String sql = "update z_project set f_isprovince = 'true', f_provincemoney = ? where id in('"+ ids +"')";
			objectDao.executeSql(sql, money);
		}else if("gjj".equals(typeid)){
			String sql = "update z_project set f_iscountry = 'true', f_countrymoney = ? where id in('"+ ids +"')";
			objectDao.executeSql(sql, money);
		}else{
			throw new BusinessException("项目级别错误，请联系管理员");
		}
	}

	/**
	 * 项目中期检查
	 * @param ids
	 * @param typeid
	 * @throws Exception
	 */
	@Override
	public void updateProjectMiddle(String ids, String typeid, String typename) throws Exception{
		String sql = "update z_project set f_ismiddle = ?,  f_ismiddletypeid = ?, f_ismiddletypename = ? where id in('"+ ids +"')";
		objectDao.executeSql(sql, "true", typeid, typename);
	}

	/**
	 * 项目结题结果
	 * @param ids
	 * @param ddmbid
	 * @param ddmbname
	 * @param cjpdid
	 * @param cjpdname
	 * @throws Exception
	 */
	@Override
	public void updateProjectEnding(String ids, String ddmbid, String ddmbname, String cjpdid, String cjpdname) throws Exception{
		String sql = "update z_project set f_isending = ?, f_endingmbid = ?, f_endingmbname = ?, f_endingcjpdid = ?, f_endingcjpdname = ? where id in('"+ ids +"')";
		objectDao.executeSql(sql, "true", ddmbid, ddmbname, cjpdid, cjpdname);
	}

	/**
	 * 根据分组ID加载项目列表
	 * @param groupid
	 * @return
	 * @throws Exception
	 */
	public List<Z_project> getListByGroupId(String groupid) throws Exception{
		String sql = "select * from z_project where f_classifyid = ? and f_delete = ?";
		return objectDao.queryBySql1(sql, groupid, '0');
	}

	/**
	 * 更新路演分数
	 * @param projectid
	 * @param scroe
	 * @throws Exception
	 */
	@Override
	public void updateLuyanScore(String projectid, String scroe) throws Exception{
		Z_project project = this.get(projectid);
		if(project != null){
			project.setF_luyanscore(scroe);
		}
	}

	/**
	 * 导入路演分数
	 * @param rootPath
	 * @param f_url
	 * @throws Exception
	 */
	@Override
	public void updateImportLuyanScore(String rootPath, String f_url) throws Exception{
		try{
			if(f_url.indexOf(".xls") == -1 && f_url.indexOf(".xlsx") == -1){
				throw new BusinessException("仅支持导入Excel文件，请重新上传");
			}
			File file = new File(rootPath + "/" + f_url); //根据文件名创建一个文件对象
			if(file == null || !file.exists()){
				throw new BusinessException("导入Excel文件不存在");
			}
			Workbook wb = Workbook.getWorkbook(file); //从文件流中取得Excel工作区对象
			int size = wb.getSheets().length;//得到Sheet数量
			if(size == 0){
				throw new BusinessException("导入Excel文件格式错误，请检查");
			}
			Sheet sheet = wb.getSheet(0);//从工作区中取得页，取得这个对象的时候既可以用名称来获得，也可以用序号。
			for (int i = 2; i < sheet.getRows()-1; i++) {
				Cell[] cells = sheet.getRow(i);
				String code = cells[1].getContents();
				double score = Double.valueOf(cells[8].getContents());
				System.out.println(code);
				System.out.println(score);
				String sql = "update z_project set f_luyanscore = ? where f_code = ?";
				objectDao.executeSql(sql, score, code);
			}
		}catch (Exception e){
			e.printStackTrace();
			throw new BusinessException("导入Excel文件格式错误，请检查" + e.getMessage());
		}
	}

	/**
	 * 加载报表列表
	 * @param start
	 * @param end
	 * @return
	 * @throws Exception
	 */
	public List<Z_project> getReportList(String start, String end) throws Exception{
		String sql = "select * from Z_project where (f_isschool = ? or f_isprovince = ? or f_iscountry = ?) and f_adddate > ? and f_adddate < ? and f_delete = ? order by f_adddate";
		return objectDao.queryBySql1(sql,"true", "true", "true", start, end, "0");
	}

	/**
	 * 加载报表列表
	 * @param start
	 * @param end
	 * @return
	 * @throws Exception
	 */
	public List<Z_project> getReportList1(String start, String end) throws Exception{
		String sql = "select * from Z_project where f_adddate > ? and f_adddate < ? and f_delete = ? order by f_adddate";
		return objectDao.queryBySql1(sql,start, end, "0");
	}

	/**
	 * 根据项目ID加载项目当前审核节点信息
	 * @param projctId
	 * @return
	 * @throws Exception
	 */
	public String getProjectAuditStep(String projctId) throws Exception{
		String key = "xmtjlc";
		String objId = key+"."+ projctId;
		ProcessInstance instance = activitiRuntimeService.createProcessInstanceQuery().processInstanceBusinessKey(objId).singleResult();
		ProcessDefinitionEntity processDefinitionEntity=(ProcessDefinitionEntity) activitiRepositoryService.getProcessDefinition(instance.getProcessDefinitionId());
		ActivityImpl activityImpl = processDefinitionEntity.findActivity(instance.getActivityId()); // 根据活动id获取活动实例
		return activityImpl.getProperties().get("name").toString();
	}

	/**
	 * 根据用户信息获得项目数量
	 * @param employee
	 * @return
	 * @throws Exception
	 */
	@Override
	public int getProjectCountByUser(A_Employee employee) throws Exception{
		if(employee.isIsadmin()){
			String sql = "select * from Z_project where f_delete = ?";
			List<Z_project> list = objectDao.queryBySql1(sql, "0");
			if(list != null && list.size() > 0){
				return list.size();
			}else{
				return 0;
			}
		}else if(employee.getDepartmentadmin().equals("true")){
			String sql = "select * from Z_project where f_branchid = ? and f_delete = ?";
			List<Z_project> list = objectDao.queryBySql1(sql, employee.getBranchid(), "0");
			if(list != null && list.size() > 0){
				return list.size();
			}else{
				return 0;
			}
		}else{
			String sql = "select * from Z_project where f_leaderid = ? and f_delete = ?";
			List<Z_project> list = objectDao.queryBySql1(sql, employee.getId(), "0");
			if(list != null && list.size() > 0){
				return list.size();
			}else{
				return 0;
			}
		}
	}

	/**
	 * 根据项目编码加载项目信息
	 * @param code
	 * @return
	 * @throws Exception
	 */
	public Z_project getObjectByCode(String code) throws Exception{
		String sql = "select * from Z_project where f_code = ?";
		List<Z_project> list = objectDao.queryBySql1(sql, code);
		if(list != null && list.size() > 0){
			return list.get(0);
		}
		return null;
	}

	/**
	 * 根据团队ID加载项目列表
	 * @param teamId
	 * @return
	 * @throws Exception
	 */
	public List<Z_project> getObjectListByTeamId(String teamId) throws Exception{
		String sql = "select * from Z_project where f_teamid = ?";
		return objectDao.queryBySql1(sql, teamId);
	}
}
